/*
 * @Author: wwssaabb
 * @Date: 2021-11-05 15:05:45
 * @LastEditTime: 2021-11-05 17:54:30
 * @FilePath: \handwritten-code\demo\实现并发限制的异步调度器.js
 */

//JS 实现一个带并发限制的异步调度器 Scheduler，保证同时运行的任务最多有两个
/* 
 a.addTask(1000, "1");
 a.addTask(500, "2");
 a.addTask(300, "3");
 a.addTask(400, "4");
 a.addTask(100, "5");
 a.addTask(500, "6");
 a.addTask(600, "7");
 a.addTask(1500, "8");
 a.addTask(2000, "9");
 a.addTask(700, "10");
 的输出顺序是： 2 3 1 5 4 6 7 8 9 10
*/

class Scheduler {
  constructor(limit) {
    this.queue = []
    this.waitQueue = []
    this.maxCount = limit
  }

  //设置任务
  task(time, order, index) {
    return new Promise(resolve => {
      setTimeout(() => resolve(order), time)
    }).then(res => {
      console.log(res)
      this.next(index)
    })
  }

  add(time, order, index) {
    this.queue.push(this.task(time, order, index))
  }
  wait(params) {
    this.waitQueue.push(Promise.resolve(params))
  }

  //添加任务
  addTask(time, order) {
    let l = this.queue.length
    console.log(l)
    if (l < this.maxCount) {
      this.add(
        time,
        order,
        l
      )
    } else {
      this.wait({
        time,
        order
      })
    }
  }

  remove(index) {
    this.queue.splice(index, 1)
  }

  //下一个任务
  async next(index) {
    let nextTask = this.waitQueue.shift()
    nextTask ? await nextTask.then(({
      time,
      order
    }) => {
      this.queue.splice(index, 1, this.task(time, order, index))
    }) : this.remove(index)
  }
}